<template>
  <div class="config-box">
    <div class="container" @dragover="onDragOver" @drop="onDrop">
      <div>
        <div class="mb-30">
          <hsa-title-box title="报表名称"></hsa-title-box>
          <div class="flex mt-10">
            <el-input
              v-model="state.queryForm.repportName"
              placeholder="请输入报表名称"
            />
            <el-button class="ml-10" @click="goBack">取消</el-button>
            <el-button type="primary">保存</el-button>
          </div>
        </div>
        <div class="mb-30">
          <hsa-title-box title="数据"></hsa-title-box>
          <div class="mt-10">
            <div class="mb-10">
              <el-select
                size="large"
                v-model="state.queryForm.dataGatherVal"
                style="width: 100%"
              >
                <el-option
                  v-for="item in state.dataGather"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="mb-10">或（选择数据表将自动生成集）</div>
            <div>
              <el-select
                size="large"
                v-model="state.queryForm.dataTabVal"
                style="width: 100%"
              >
                <el-option
                  v-for="item in state.dataTab"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>
        </div>
        <div class="mb-30 flex just-btw">
          <el-button type="primary" @click="setRule">规则</el-button>
          <div>
            <el-button type="primary" @click="setDimension">分组维度</el-button>
            <el-button type="primary" @click="setStructure"
              >新配置结构</el-button
            >
          </div>
        </div>
        <div class="mb-30">
          <div class="flex just-btw al-cen mb-10">
            <hsa-title-box title="维度"></hsa-title-box>
            <el-input
              style="width: 200px"
              class="input-with-select"
              v-model="state.dimensionVal"
            >
              <template #append>
                <el-button :icon="Search" />
              </template>
            </el-input>
          </div>
          <div>
            <el-tree
              :data="state.dimensionTree"
              node-key="id"
              draggable
              :allow-drop="handleAllowDrop"
              :allow-drag="handleAllowDrag"
              style="max-width: 600px"
              @node-drag-start="handleDragStart"
              @node-drag-over="handleDragOver"
            />
          </div>
        </div>
        <div class="mb-30">
          <div class="flex just-btw al-cen">
            <hsa-title-box title="度量"></hsa-title-box>
            <el-input
              style="width: 200px"
              class="input-with-select"
              v-model="state.measurementVal"
            >
              <template #append>
                <el-button :icon="Search" />
              </template>
            </el-input>
          </div>
          <div>
            <el-tree
              :data="state.measurementTree"
              node-key="id"
              draggable
              :allow-drop="handleAllowDrop"
              :allow-drag="handleAllowDrag"
              style="max-width: 600px"
              @node-drag-start="handleDragStartCol"
              @node-drag-over="handleDragOver"
            />
          </div>
        </div>
      </div>
      <div>
        <div class="mb-30">
          <hsa-title-box title="字段"></hsa-title-box>
          <div class="mt-10 field-box">
            <div class="field-title mb-10">行<i>（可多行）</i></div>
            <div class="field-move mb-10" data-key="dimension">
              拖动维度字段至此处
            </div>
            <ul class="field-list">
              <li v-for="(it, i) in state.rowList" :key="i">
                <div>{{ it.label || "" }}</div>
                <div class="field-tip">
                  <el-tooltip placement="right-start">
                    <template #content>
                      <div>
                        <div @click="riseOrder(state.rowList,i)" style="cursor: pointer;">升序</div>
                        <div @click="dropOrder(state.rowList,i)" style="cursor: pointer;">降序</div>
                        <div style="cursor: pointer;">显示</div>
                        <div style="cursor: pointer;">隐藏</div>
                        <div style="cursor: pointer;">去0</div>
                      </div>
                    </template>
                    <img
                      class="field-more"
                      src="./images/icon_more.png"
                      alt=""
                      srcset=""
                    />
                  </el-tooltip>
                </div>
              </li>
            </ul>
          </div>
          <div class="field-change">
            <img
              src="./images/icon_change.png"
              alt=""
              srcset=""
              @click="swapArr"
            />
          </div>
          <div class="mt-10 field-box mb-30">
            <div class="field-title mb-10">列<i>（可多列）</i></div>
            <div class="field-move mb-10" data-key="measurement">
              拖动度量字段至此处
            </div>
            <ul class="field-list">
              <li v-for="(it, i) in state.colList" :key="i">
                <div>{{ it.label || "" }}</div>
                <div class="field-tip">
                  <el-tooltip placement="right-start">
                    <template #content>
                      <div class="tip-box">
                        <div @click="riseOrder(state.colList,i)">升序</div>
                        <div @click="dropOrder(state.colList,i)">降序</div>
                        <div>显示</div>
                        <div>隐藏</div>
                        <div>去0</div>
                      </div>
                    </template>
                    <img
                      class="field-more"
                      src="./images/icon_more.png"
                      alt=""
                      srcset=""
                    />
                  </el-tooltip>
                </div>
              </li>
            </ul>
          </div>
          <div class="field-box mb-30">
            <div class="field-title mb-10 flex just-btw al-cen">
              <div>过滤器</div>
              <el-button type="primary" @click="filterHandle">新增</el-button>
            </div>
            <div class="filter-box">
              <el-tag
                size="large"
                v-for="(it, i) in state.filterList"
                :key="i"
                closable
                @click="editFilter(it)"
                @close="delFilter(i)"
              >
                {{ it.name }}
              </el-tag>
            </div>
          </div>
          <div v-if="state.changeNum == 1">
            <div class="flex just-btw al-cen mb-30">
              <div>聚合内容</div>
              <div>
                <el-select size="large" style="width: 100px">
                  <el-option
                    v-for="item in state.aggregationType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </div>
            <div>
              <hsa-title-box title="计算"></hsa-title-box>
              <div class="mt-10">
                <el-input
                  style="width: 100%"
                  :rows="3"
                  type="textarea"
                  placeholder="Please input"
                />
              </div>
            </div>
          </div>
          <div class="flex change-btn">
            <div
              :class="{ active: state.changeNum == 1 }"
              @click="state.changeNum = 1"
            >
              聚合
            </div>
            <div
              :class="{ active: state.changeNum == 2 }"
              @click="state.changeNum = 2"
            >
              明细
            </div>
          </div>
        </div>
      </div>
      <div>
        <div class="mb-30">
          <hsa-title-box title="查询条件"></hsa-title-box>
          <div class="query-box mt-10">
            <div>
              <el-tag
                size="large"
                v-for="(tag, i) in state.tagList"
                :key="i"
                closable
                @click="editTag(tag)"
                @close="delTag(i)"
              >
                {{ tag.name }}
              </el-tag>
            </div>
            <el-button type="primary" @click="addQuery">新增</el-button>
          </div>
        </div>
        <div>
          <div class="flex just-btw al-cen mb-30">
            <hsa-title-box title="自助分析结果"></hsa-title-box>
            <div class="flex">
              <div class="flex al-cen mr-20">
                <span class="mr-10">自动刷新</span>
                <el-switch />
              </div>
              <el-button type="primary">手动刷新</el-button>
              <el-button type="primary">撤销</el-button>
              <el-button type="primary">重做</el-button>
              <el-button type="primary">下钻</el-button>
              <el-button type="primary">上卷</el-button>
              <el-button type="primary" @click="showView">预览</el-button>
            </div>
          </div>
          <div>
            <t-table
              :table="table"
              :columns="table.columns"
              @page-change="pageChange"
              @size-change="sizeChange"
              isPaginationCumulative
            />
          </div>
        </div>
      </div>
    </div>
    <rule-config ref="myRule" @sureHandle="sureRuleHandle" />
    <grouping-dimension ref="myDimension" @sureHandle="sureDimensionHandle" />
    <config-structure ref="myStructure" @sureHandle="sureStructureHandle" />
    <query-edit ref="myQueryEdit" @sureHandle="sureHandle" />
    <filter-edit ref="myFilterEdit" @sureHandle="sureFilterHandle" />
  </div>
</template>

<script setup lang="ts">
import ruleConfig from "./model/rule-config.vue";
import groupingDimension from "./model/grouping-dimension.vue";
import configStructure from "./model/config-structure.vue";
import queryEdit from "./model/query-edit.vue";
import filterEdit from "./model/filter-edit.vue";
import { ref, onMounted, computed, reactive } from "vue";
import { Search, Edit, Delete } from "@element-plus/icons-vue";
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const customDragImage = ref(null);
const moveData = ref();
const myRule = ref(null);
const myDimension = ref(null);
const myStructure = ref(null);
const myFilterEdit = ref(null);
const myQueryEdit = ref(null);

const state = reactive({
  queryForm: {
    repportName: "", //报表名称
    dataGatherVal: "", //数据集
    dataTabVal: "", //数据表
  },
  dataGather: [
    //数据集
    {
      value: "1",
      label: "xxx数据集",
    },
    {
      value: "2",
      label: "数据集",
    },
  ],
  dataTab: [
    //数据表
    {
      value: "1",
      label: "xxx数据表",
    },
    {
      value: "2",
      label: "数据表",
    },
  ],
  dimensionTree: [
    //维度
    {
      label: "节点1",
      id: "1",
      children: [
        {
          label: "节点1-1",
          id: "1-1",
        },
      ],
    },
    {
      label: "节点2",
      id: "2",
      children: [
        {
          label: "节点2-1",
          id: "2-1",
        },
        {
          label: "节点2-2",
          id: "2-2",
        },
      ],
    },
    {
      label: "节点3",
      id: "3",
      children: [
        {
          label: "节点3-1",
          id: "3-1",
        },
        {
          label: "节点3-2",
          id: "3-2",
        },
      ],
    },
  ],
  dimensionVal: "",
  measurementTree: [
    //维度
    {
      label: "节点1",
      id: "1",
      children: [
        {
          label: "节点1-1",
          id: "1-1",
        },
      ],
    },
    {
      label: "节点2",
      id: "2",
      children: [
        {
          label: "节点2-1",
          id: "2-1",
        },
        {
          label: "节点2-2",
          id: "2-2",
        },
      ],
    },
    {
      label: "节点3",
      id: "3",
      children: [
        {
          label: "节点3-1",
          id: "3-1",
        },
        {
          label: "节点3-2",
          id: "3-2",
        },
      ],
    },
  ],
  measurementVal: "",
  rowList: [], //行
  colList: [], //列
  aggregationType: [
    //聚合内容
    {
      value: "1",
      label: "加",
    },
    {
      value: "2",
      label: "减",
    },
    {
      value: "3",
      label: "乘",
    },
    {
      value: "4",
      label: "除",
    },
  ],
  changeNum: 1, //1、聚合；2、明细
  filterList: [], //过滤参数列表
  tagList: [], //查询参数列表
});


onMounted(() => {
  console.log(route.query,'route.query');
  setDragDemo();
});

const goBack = () => {
  router.back()
};
const setRule = () => {
  myRule.value.open();
};

const sureRuleHandle = (data) => {
  // state.filterList.push(data);
  console.log(data, "33344");
};

const setDimension = () => {
  myDimension.value.open();
};

const sureDimensionHandle = (data) => {
  // state.filterList.push(data);
  console.log(data, "33344");
};

const setStructure = () => {
  myStructure.value.open();
};

const sureStructureHandle = (data) => {
  // state.filterList.push(data);
  console.log(data, "33344");
};

const setDragDemo = () => {
  //生成一个div，用户替换拖拽框
  const div = document.createElement("div");
  div.style.width = "250px";
  div.style.height = "50px";
  div.style.borderRadius = "6px";
  div.style.border = "2px solid #dbe6ff";
  div.style.backgroundColor = "#585c71";
  div.style.position = "absolute";
  div.style.top = "-9999px";
  document.body.appendChild(div);
  customDragImage.value = div;
};
// 处理拖放事件,阻止默认行为，关闭禁止图标
const onDragOver = (event) => {
  event.preventDefault();
};

//处理拖拽结束
const onDrop = (event) => {
  event.preventDefault();
  if (moveData.value.key == event.target.dataset.key) {
    if (event.target.dataset.key == "dimension") {
      if (!state.rowList.some((item) => item.id === moveData.value.data.id)) {
        state.rowList.push(moveData.value.data);
      }
    }
    if (event.target.dataset.key == "measurement") {
      if (!state.colList.some((item) => item.id === moveData.value.data.id)) {
        state.colList.push(moveData.value.data);
      }
    }
  }
};

// 只允许叶子节点拖动
const handleAllowDrag = (node) => {
  return node.isLeaf;
};

// 不允许放置
const handleAllowDrop = () => {
  return false;
};

// 拖拽开始
const handleDragStart = (node, event) => {
  handleSetDate(node, event, "dimension");
};
// 拖拽开始
const handleDragStartCol = (node, event) => {
  handleSetDate(node, event, "measurement");
};

const handleSetDate = (node, event, key) => {
  if (customDragImage.value) {
    //储存被拖拽的数据
    moveData.value = {
      key,
      data: node.data,
    };
    //修改拖拽框样式
    customDragImage.value.innerHTML = `
    <div style="color: white; padding:0 10px; font-size: 16px;line-height:50px;cursor: move;">
        <div>${node.data.label}</div>
    </div>`;
    //setDragImage方法的三个参数，第一个是替换的dom，第二三个参数是拖动时鼠标在替换dom中的位置
    event.dataTransfer.setDragImage(customDragImage.value, 125, 25);
  }
};

// 拖拽过程中修改鼠标样式，使其不出现禁止图标
const handleDragOver = (draggingNode, dropNode, event) => {
  event.dataTransfer.dropEffect = "move";
};

const swapArr = () => {
  // 直接交换两个数组的引用
  [state.rowList, state.colList] = [state.colList, state.rowList];
};
const filterHandle = () => {
  myFilterEdit.value.open("新增");
};
const editFilter = (data) => {
  myFilterEdit.value.open("编辑", data);
};
const delFilter = (i) => {
  state.filterList.splice(i,1)
};

const sureFilterHandle = (data) => {
  state.filterList.push(data);
  console.log(state.filterList, "33344");
};
const riseOrder = (arr,index) => {
  arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]))
};
const dropOrder = (arr,index) => {
  arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]))
};

const addQuery = () => {
  myQueryEdit.value.open("新增");
};
const editTag = (data) => {
  myQueryEdit.value.open("编辑", data);
};
const delTag = (i) => {
  state.tagList.splice(i,1)
};


const sureHandle = (data) => {
  state.tagList.push(data);
  console.log(state.tagList, "33344");
};

const table = ref<TableTypes.Table>({
  data: [
    {
      id: "1",
      date: "2019-09-25",
      date1: "2019-09-26",
      name: "张三",
      status: "2",
      address: "广东省广州市天河区",
    },
    {
      id: "2",
      date: "2019-09-26",
      date1: "2019-09-27",
      name: "张三1",
      status: "1",
      address: "广东省广州市天广东省广州市天河区2广东省广州市天河区2河区2",
    },
    {
      id: "3",
      date: "2019-09-26",
      date1: "2019-09-28",
      name: "张三1",
      status: "1",
      address: "广东省广州市天广东省广州市天河区2广东省广州市天河区2河区2",
    },
    {
      id: "4",
      date: "2019-09-26",
      name: "张三1",
      status: "1",
      address: "广东省广州市天广东省广州市天河区2广东省广州市天河区2河区2",
    },
  ],
  firstColumn: { type: "index", width: 80, fixed: true },
  total: 20,
  currentPage: 1,
  pageSize: 10,
  layout: "total,sizes, slot, prev, pager, next, jumper",
  prevText: "上一页",
  nextText: "下一页",
  // 接口返回数据
  //   data: [],
  // 表头数据
  columns: [
    { prop: "name", label: "报表名称", minWidth: "100" },
    { prop: "date", label: "创建人", minWidth: "180" },
    { prop: "status", label: "创建时间", minWidth: "80" },
    { prop: "address", label: "所属团队", minWidth: "220" },
  ],
  // 表格内操作列
  // operator: [
  // {
  //   text: "权限",
  //   fun: viewDetail,
  //   noshow: [{ key: "status", val: ["1"] }]
  // },
  // {
  //   text: "编辑",
  //   fun: edit
  // },
  // {
  //   text: "删除",
  //   fun: del,
  //   bind: {
  //     type: 'danger',
  //     text: true
  //   }
  // }
  // ],
  // 操作列样式
  // operatorConfig: {
  //   // fixed: "right", // 固定列表右边（left则固定在左边）
  //   width: 280,
  //   label: "操作"
  // }
});

// 选择当前页码
const pageChange = (page) => {
  console.log("选择当前页码", page);
  table.value.currentPage = page;
  //   getData(val)
};
// 选择当页条数
const sizeChange = (size) => {
  console.log("选择当页条数", size);
  table.value.currentPage = 1;
  table.value.pageSize = size;
  //   getData(val)
};
const showView = () => {
  router.push('/self-analysis/config-preview')
  // router.push({path:'/self-analysis/config-preview',query:{id:val.id}})
};
</script>
<style scoped lang="scss">
.flex {
  display: flex;
}
.just-btw {
  justify-content: space-between;
}
.al-cen {
  align-items: center;
}
.ml-10 {
  margin-left: 10px;
}
.mr-10 {
  margin-right: 10px;
}
.mr-20 {
  margin-right: 20px;
}
.mt-10 {
  margin-top: 10px;
}
.mb-10 {
  margin-bottom: 10px;
}
.mb-20 {
  margin-bottom: 20px;
}
.mb-30 {
  margin-bottom: 30px;
}
.config-box {
  width: 100%;
  height: 100%;
  .container {
    display: grid;
    grid-template-columns: 2fr 2fr 5fr;
    gap: 8px;
    height: 100%;
    > div {
      background: #fff;
      padding: 20px 10px;
      box-sizing: border-box;
      position: relative;
      &:nth-child(2){
        padding-bottom: 50px;
      }
    }
    .field-box {
      width: 100%;
      .field-title {
        font-size: 16px;
        i {
          font-size: 12px;
        }
      }
      .field-move {
        width: 100%;
        text-align: center;
        line-height: 40px;
        border: 1px dashed #000;
      }
      .field-list {
        width: 100%;
        li {
          width: 100%;
          text-align: center;
          line-height: 30px;
          border: 1px solid #000;
          position: relative;
          margin-bottom: 6px;
          .field-tip {
            position: absolute;
            right: 10px;
            top: 3px;
            .field-more {
              width: 10px;
              height: 24px;
              object-fit: contain;
            }
          }
        }
      }
    }
    .filter-box {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
    }
    .field-change {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      margin: 20px 0;
      img {
        width: 35px;
        height: 37px;
        object-fit: contain;
      }
    }
    .change-btn {
      position: absolute;
      bottom: 10px;
      width: calc(100% - 20px);
      line-height: 30px;
      > div {
        width: 50%;
        border: 1px solid #eee;
        box-sizing: border-box;
        text-align: center;
        cursor: pointer;
        &.active {
          background-color: #02a7f0;
          color: #fff;
        }
      }
    }
    .query-box {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      > div {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
      }
    }
  }
}
</style>
